import { getUserInfo, login } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'

const state = {
  token: getToken(),
  userInfo: {}
  // 删除token

}

const mutations = {
  setToken: (state, token) => {
    state.token = token // 存仓库
    setToken(token) // 持久化存本地
  },
  // 清除token
  removeToken(state) {
    state.token = null

    removeToken() // 删除token
  },
  setUserInfo: (state, userInfo) => {
    state.userInfo = userInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  logout({ commit }) {
    commit('removeToken')
    commit('removeUserInfo')
  },

  async login({ commit }, obj) {
    // setTimeout(() => {
    //   commit('setToken', 'token')
    // }, 2000)
    const res = await login(obj)
    console.log(res)
    commit('setToken', res)
  },
  async getUserInfo({ commit }) {
    // setTimeout(() => {
    //   commit('setUserInfo', { name: '张三' })
    // }, 2000)
    const res = await getUserInfo()
    console.log(res)
    commit('setUserInfo', res)
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
